<template>
  <div class="custom_page">
    <!-- 搜索表单 -->
    <el-card class="search-card">
      <el-form :model="formParams" label-width="100px" ref="searchFormRef">
        <el-row :gutter="20">
          <el-col :span="24" :md="6">
            <el-form-item label="用户昵称" prop="name">
              <el-input v-model="formParams.name" placeholder="请输入用户昵称" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="24" :md="6">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="formParams.phone" placeholder="请输入手机号" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="24" :md="6">
            <el-form-item label="用户标签" prop="labelId">
              <el-select v-model="formParams.labelId" placeholder="请选择用户标签" clearable>
                <el-option
                  v-for="item in labelList"
                  :key="item.labelId"
                  :label="item.labelName"
                  :value="item.labelId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24" :md="6">
            <el-form-item label="累计消费金额" prop="minMoney">
              <el-input v-model="formParams.minMoney" placeholder="最小值">
                <template #append>至</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24" :md="6" :md-offset="18">
            <el-form-item label="" prop="maxMoney" label-width="0">
              <el-input v-model="formParams.maxMoney" placeholder="最大值" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" class="text-align-right">
            <el-button type="primary" @click="getAll">查询</el-button>
            <el-button @click="clear">重置</el-button>
            <el-button type="success" @click="exportData">导出</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 表格 -->
    <div class="table-container">
      <el-table
        :data="tableData"
        v-loading="loading.table"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="用户昵称" />
        <el-table-column prop="phone" label="手机号" />
        <el-table-column prop="memberLevelName" label="会员等级" />
        <el-table-column prop="totalConsumAmount" label="消费总额">
          <template #default="{ row }">
            {{ row.totalConsumAmount || 0 }}
          </template>
        </el-table-column>
        <el-table-column prop="buyers" label="购买次数" />
        <el-table-column prop="credit" label="剩余积分" />
        <el-table-column prop="createTime" label="注册时间" />
        <el-table-column prop="registerIp" label="注册IP" />
        <el-table-column prop="lastLoginIp" label="最后登录ip" />
        <el-table-column label="操作" width="160" fixed="right">
          <template #default="{ row }">
            <div class="table-actions">
              <el-button type="primary" link size="small" @click="details(row)">详情</el-button>
              <el-button type="primary" link size="small" @click="setPoints(row)"
                >设置积分</el-button
              >
              <el-button type="primary" link size="small" @click="tagMember(row)">打标签</el-button>
              <el-button type="danger" link size="small" @click="addToBlacklist(row)"
                >加入黑名单</el-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-wrapper">
      <el-pagination
        :current-page="formParams.page"
        :page-size="formParams.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 详情组件 -->
    <MemberDetails ref="memberDetailsRef" />
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue'
  import { useRouter } from 'vue-router'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import {
    customerMageGetAll,
    getLabels,
    addLabel,
    addTips,
    getMemberlevel,
    MemberItem,
    MemberLevelItem,
    LabelItem
  } from '@/api/memberApi'
  import MemberDetails from './details.vue'

  const router = useRouter()

  // 表格数据
  const tableData = ref<MemberItem[]>([])
  const total = ref(0)
  const loading = ref({
    table: false
  })

  // 搜索表单
  const formParams = ref({
    name: '', // 用户昵称
    phone: '', // 手机号
    labelId: '', // 标签id（原memberLevelId应为labelId）
    minMoney: null, // 累计消费金额最小值（应为数字类型）
    maxMoney: null, // 累计消费金额最大值（应为数字类型）
    page: 1,
    pageSize: 10
  })

  // 会员等级相关
  const memberLevelList = ref<MemberLevelItem[]>([])

  // 标签列表
  const labelList = ref<LabelItem[]>([])

  // 详情组件引用
  const memberDetailsRef = ref()

  // 多选
  const multipleSelection = ref<MemberItem[]>([])

  // 处理多选
  const handleSelectionChange = (val: MemberItem[]) => {
    multipleSelection.value = val
  }

  // 处理分页
  const handleSizeChange = (val: number) => {
    formParams.value.pageSize = val
    getAll()
  }

  const handleCurrentChange = (val: number) => {
    formParams.value.page = val
    getAll()
  }

  // 获取所有会员等级
  const getMemberLevels = async () => {
    try {
      const res = await getMemberlevel({ page: 1, pageSize: 1000 })
      if (res.code === '200') {
        memberLevelList.value = res.data?.list || []
      }
    } catch (error) {
      console.error('获取会员等级失败:', error)
      ElMessage.error('获取会员等级失败')
    }
  }

  // 获取所有标签
  const getLabelList = async () => {
    try {
      const res = await getLabels({})
      if (res.code === '200') {
        labelList.value = res.data || []
      }
    } catch (error) {
      console.error('获取标签列表失败:', error)
      ElMessage.error('获取标签列表失败')
    }
  }

  // 清除
  const clear = () => {
    formParams.value = {
      name: '', // 用户昵称
      phone: '', // 手机号
      labelId: '', // 标签id
      minMoney: null, // 累计消费金额最小值
      maxMoney: null, // 累计消费金额最大值
      page: 1,
      pageSize: 10
    }
    getAll()
  }

  // 详情
  const details = (row: MemberItem) => {
    memberDetailsRef.value?.getUser({
      buyerUserId: row.buyerUserId
    })
  }

  // 设置积分
  const setPoints = (row: MemberItem) => {
    ElMessageBox.prompt('请输入积分值', '设置积分', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPattern: /^\d+$/,
      inputErrorMessage: '请输入有效的积分值'
    })
      .then(({ value }) => {
        // 这里应该调用设置积分的API
        ElMessage.success(`成功为用户 ${row.name} 设置积分: ${value}`)
      })
      .catch(() => {
        ElMessage.info('取消设置积分')
      })
  }

  // 打标签
  const tagMember = (row: MemberItem) => {
    ElMessageBox.prompt('请输入标签', '打标签', {
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    })
      .then(({ value }) => {
        // 这里应该调用打标签的API
        ElMessage.success(`成功为用户 ${row.name} 添加标签: ${value}`)
      })
      .catch(() => {
        ElMessage.info('取消打标签')
      })
  }

  // 加入黑名单
  const addToBlacklist = (row: MemberItem) => {
    ElMessageBox.confirm(`确定要将用户 ${row.name} 加入黑名单吗？`, '加入黑名单', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(() => {
        // 这里应该调用加入黑名单的API
        ElMessage.success(`成功将用户 ${row.name} 加入黑名单`)
      })
      .catch(() => {
        ElMessage.info('取消操作')
      })
  }

  // 导出
  const exportData = () => {
    ElMessage.info('导出功能待实现')
  }

  // 重置
  const reset = () => {
    getAll()
  }

  // 获取所有数据
  const getAll = async () => {
    loading.value.table = true
    try {
      // 处理参数，确保null值不会传递
      const params = { ...formParams.value }
      if (params.minMoney === null) {
        delete params.minMoney
      }
      if (params.maxMoney === null) {
        delete params.maxMoney
      }

      const res = await customerMageGetAll(params)
      if (res.code === '200') {
        tableData.value = res.data?.list || []
        total.value = res.data?.total || 0
      }
    } catch (error) {
      console.error('获取会员列表失败:', error)
      ElMessage.error('获取会员列表失败')
    } finally {
      loading.value.table = false
    }
  }

  onMounted(() => {
    getAll()
    getMemberLevels()
    getLabelList()
  })
</script>

<style lang="scss" scoped>
  .custom_page {
    padding: 20px;
    margin-top: 20px;
    background-color: var(--art-main-bg-color);
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }

  .search-card {
    margin-bottom: 20px;
    border-radius: 8px;
    box-shadow: 0 1px 6px 0 rgba(0, 0, 0, 0.05);
    background-color: var(--art-main-bg-color);
  }

  .table-container {
    width: 100%;
    overflow-x: auto;
    margin-bottom: 20px;
    border-radius: 8px;
    box-shadow: 0 1px 6px 0 rgba(0, 0, 0, 0.05);
    background-color: var(--art-main-bg-color);
  }

  .text-align-right {
    text-align: right;
  }

  .dialog-footer {
    text-align: right;
  }

  // 表格操作按钮样式调整
  .table-actions {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 5px;
  }

  // 媒体查询 - 响应式设计
  @media screen and (max-width: 768px) {
    .custom_page {
      padding: 10px;
      margin-top: 10px;
    }

    .search-card {
      margin-bottom: 15px;
    }

    .table-container {
      margin-bottom: 15px;
    }

    .pagination-wrapper {
      margin-top: 15px;
    }

    // 小屏幕下搜索表单标签宽度调整
    :deep(.el-form-item__label) {
      font-size: 12px;
      padding-right: 5px;
    }

    // 小屏幕下表格操作按钮垂直排列
    .table-actions {
      flex-direction: column;
      align-items: flex-start;
      gap: 3px;
    }

    // 小屏幕下表格单元格内容调整
    :deep(.el-table__cell) {
      padding: 5px 0;
      font-size: 12px;
    }

    // 小屏幕下表格标题调整
    :deep(.el-table th) {
      font-size: 12px;
    }
  }

  // 媒体查询 - 大屏幕优化
  @media screen and (min-width: 1200px) {
    .custom_page {
      max-width: 1400px;
      margin: 20px auto;
    }
  }

  // 修复固定列透明问题
  .table-container {
    :deep(.el-table__fixed-right) {
      background-color: var(--art-bg-color);
    }
    :deep(.el-table__fixed-right .el-table__body) {
      background-color: var(--art-bg-color);
    }
    :deep(.el-table__fixed-right .el-table__row) {
      background-color: var(--art-bg-color);
    }
    :deep(.el-table__fixed-right .el-table__cell) {
      background-color: var(--art-bg-color);
    }
    :deep(.el-table__fixed-right .el-table__row--striped .el-table__cell) {
      background-color: var(--art-bg-color);
    }
  }

  // 优化表格列样式
  :deep(.el-table th) {
    background-color: var(--art-gray-100);
    font-weight: 600;
  }

  :deep(.el-table .el-table__cell) {
    padding: 8px 0;
  }

  // 优化分页样式
  .pagination-wrapper {
    margin-top: 20px;
    box-sizing: border-box;
    overflow-x: auto !important;
    overflow-y: hidden !important;
    -webkit-overflow-scrolling: touch !important;
    overscroll-behavior: contain !important;
    touch-action: pan-x !important;
  }

  :deep(.el-pagination) {
    display: flex !important;
    flex-wrap: nowrap !important;
    align-items: center !important;
    justify-content: flex-start !important;
    width: auto !important;
    margin: 0 !important;
    padding: 20px 0;
    background-color: var(--art-main-bg-color);
    border-radius: 8px;
    box-shadow: 0 1px 6px 0 rgba(0, 0, 0, 0.05);
  }

  // 调整分页组件元素间距和显示
  :deep(.el-pagination__sizes),
  :deep(.el-pagination__total) {
    margin-right: 10px !important;
    margin-left: 0 !important;
    white-space: nowrap !important;
    flex-shrink: 0 !important;
  }

  :deep(.el-pagination__prev),
  :deep(.el-pagination__next),
  :deep(.el-pagination__number) {
    margin: 0 2px !important;
    padding: 0 8px !important;
  }

  // 表格容器优化
  .table-container {
    width: 100%;
    overflow-x: auto;
    overflow-y: auto !important;
    margin-bottom: 20px;
    border-radius: 8px;
    box-shadow: 0 1px 6px 0 rgba(0, 0, 0, 0.05);
    background-color: var(--art-main-bg-color);
    -webkit-overflow-scrolling: touch !important;
    touch-action: pan-y !important;
  }
</style>
